<?php

namespace app\common\services;

use app\models\IntegralRecord;
use app\models\Recommend;
use app\models\User;

class StaticServices {
  public static $page = 50;

  public static function is_idcard($id)
  {
    $id = strtoupper($id);
    $regx = "/(^\d{15}$)|(^\d{17}([0-9]|X)$)/";
    $arr_split = [];
    if (!preg_match($regx, $id)) {
      return false;
    }
    if (15 == strlen($id)) { //检查15位
      $regx = "/^(\d{6})+(\d{2})+(\d{2})+(\d{2})+(\d{3})$/";

      @preg_match($regx, $id, $arr_split);
      //检查生日日期是否正确
      $dtm_birth = '19' . $arr_split[2] . '/' . $arr_split[3] . '/' . $arr_split[4];
      if (!strtotime($dtm_birth)) {
        return false;
      } else {
        return true;
      }
    } else { //检查18位
      $regx = "/^(\d{6})+(\d{4})+(\d{2})+(\d{2})+(\d{3})([0-9]|X)$/";
      @preg_match($regx, $id, $arr_split);
      $dtm_birth = $arr_split[2] . '/' . $arr_split[3] . '/' . $arr_split[4];
      if (!strtotime($dtm_birth)) { //检查生日日期是否正确
        return false;
      } else {
        //检验18位身份证的校验码是否正确。
        //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
        $arr_int = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
        $arr_ch = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
        $sign = 0;
        for ($i = 0; $i < 17; $i++) {
          $b = (int)$id{$i};
          $w = $arr_int[$i];
          $sign += $b * $w;
        }
        $n = $sign % 11;
        $val_num = $arr_ch[$n];
        if ($val_num != substr($id, 17, 1)) {
          return false;
        } //phpfensi.com
        else {
          return true;
        }
      }
    }
  }

  public static function includeAppJs($path, $depend)
  {
    return self::includeApp('js', $path, $depend);
  }

  public static function includeAppCss($path, $depend)
  {
    return self::includeApp('css', $path, $depend);
  }

  private static function includeApp($type, $path, $depend)
  {
    if ($type == 'js') {
      \Yii::$app->getView()->registerJsFile($path, ['depends' => $depend]);
    }
    if ($type == 'css') {
      \Yii::$app->getView()->registerCssFile($path, ['depends' => $depend]);
    }
  }

  public static function getRandChar($length = 6)
  {
    $str = null;
    $strPol = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
    $max = strlen($strPol) - 1;

    for ($i = 0; $i < $length; $i++) {
      $str .= $strPol[rand(0, $max)]; //rand($min,$max)生成介于min和max两个数之间的一个随机整数
    }

    return $str;
  }

  //mt_rand(100000, 999999)
  public static function getCode($code, $template, $phone)
  {
    $shortMessage = new ShortMessageServices();
    $shortMessage->CreateCode($code, mt_rand(100, 999), $template, '投教大观', $phone);
  }

  public static function getIP()
  {
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
      return $_SERVER['HTTP_X_FORWARDED_FOR'];
    }

    return isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
  }
}